import { LayoutConfigType, Post } from '@/app/api';
import { defineStore } from 'pinia';
export const MockStore = defineStore('mock', {
  state: () => ({
    layoutConfig: {
      prefixCls: 'demo',
      logo: 'https://next.antdv.com/assets/logo.1ef800a8.svg',
      systemName: 'LAYOUT DEMO',
      version: '1.0.0',
      theme: 'dark',
      layout: 'side',
      locale: 'zh-CN',
      collapsed: false,
      menuData: [],
      selectedKeys: [],
      openKeys: [],
      tabs: [],
      tabActiveKey: ''
    } as LayoutConfigType,
    posts: [] as Post[]
  }),
  getters: {
    initPosts: async state => {
      if (!state || !state.posts || state.posts.length === 0) {
        const posts = await getTypicodeData("posts");
        if (posts && posts.length > 0) {
          state.posts = posts.reverse();
        }
      }
      return state.posts;
    }
  },
  actions: {
    async getLayoutConfig() {
      return this.layoutConfig;
    },
    async postList() {
      return await this.initPosts;
    },
    async setPost(post: Post) {
      const posts = await this.initPosts
      let id = 1;
      if (posts && posts.length > 0) {
        id = posts[0].id + 1
      }
      this.posts.unshift({ ...post, id: id });
      return post;
    },
    async setPosts(posts: Post[]) {
      this.posts = posts;
      return this.posts;
    },
    async deletePost(id: number) {
      const posts = await this.postList();
      if (posts && posts.length > 0) {
        await this.setPosts(posts.filter(item => item.id !== id));
      }
    },
    async deleteBatchPost(ids: number[]) {
      const posts = await this.postList();
      if (posts && posts.length > 0) {
        await this.setPosts(posts.filter(item => !ids.some(id => id === item.id)));
      }
    }
  }
});
export async function getTypicodeData(api: string) {
  const resp = await $api.GET(`/typicode/${api}`)
  if (resp.status && resp.data) {
    return resp.data
  }
  return null;
}
